|
|
|
|
|
|
|
Public Function NumAverage(inpt1 As Single, inpt2 As Single) As Single
NumAverage = (inpt1 + inpt2) / 2
End Function |
|
|
|
|
|
|
|
|
|
Although your function code can assign a value to the function multiple times, only the last value assigned before the end (or exit) of the function is returned.  |
|
|
|
|
|
|
|
|
|
|
When you call a function, you typically assign its return value to a variable in your program, or use the value in a conditional statement as shown here: |
|
|
|
|
|
|
|
|
'Assigning a function to a variable
fAvgNum = NumAverage(25, 15)
'Using a function in a conditional expression
If NumAverage(num1, num2) > 20 Then MsgBox "What an average!" |
|
|
|
|
|
|
|
|
|
If you need your function to simply perform a task (opening a database, for example), you can call the function the same way that you would call a procedure, throwing away the return value.  |
|
|
|
|
|
|
| |
|
|
|
|
There are a number of functions built and demonstrated in the FUNCDEMO.VBP project, which you can download from www.mcp.com/info. |
|
|
|
|
|
|
|
|
|
|
Determining the Scope of Procedures and Functions |
|
|
|
|
|
|
|
|
When you create a procedure (or function), you might want to limit where it can be used and how resources are allocated to make its code available to other parts of your program. Where a procedure can be called from is referred to as the scope of the procedure. |
|
|
|
|
|
|
|
|
Procedures can be defined in either of two ways: as public procedures or as private procedures. Which of these keywords you use in the Sub statement determines which other procedures or programs have access to your procedure. |
|
|
|
|
|
|
|
|
|
The scope of procedures and functions is related to the scope of variables, which is discussed in the section titled "Determining Where a Variable Can Be Used" in Chapter 9, "Using Variables to Store Information."  |
|
|
|
|
|
|
|
|
|
|
See "Determining Where a Variable Can Be Used," p. 166 |
|
|
|
|
|
|
|
|
If you want to have your procedure or function available throughout your program, you need to use the Public keyword when you define the procedure. Using the Public keyword allows a procedure defined in one form or module to be called from another form or module. However, you have to be careful with the names of public procedures because each public procedure must have a name that is unique throughout the current scope. |
|
|
|
|
|
|
|
|
If you omit the keywords Public and Private from the Sub statement, the procedure is set up by default as a public procedure. |
|
|
|
|
|